package training.dao;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import training.controller.CustomerController;
import training.vo.Login;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
/**
 * @author fatsung
 * 登入AD Server
 *
 */
@Repository("LoginADDao")
public class LoginADDao {
	private static Logger log=LoggerFactory.getLogger(LoginADDao.class);
	private static final String br="\r\n";
	private static final String address="http://192.168.6.70/AuthServices/Authentication.asmx";
	private static final String adString="<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><GetUserAttributes xmlns=\"http://masterlink.com.tw/\"><sAMAccountName>adUser</sAMAccountName></GetUserAttributes></soap:Body></soap:Envelope>";
	/**
	 * @param url
	 * @param req1
	 * @param encode
	 * @return
	 */
	public Login postURL(String req1, String password){
		Login login = new Login();
		StringBuffer sb = new StringBuffer();
		String req=adString.replaceAll("adUser", req1);
		try {
			URL url = new URL(address);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setAllowUserInteraction(true);
			http.setDoInput(true);
			http.setDoOutput(true);
			http.setRequestMethod("POST");
			http.setRequestProperty("Content-type", "text/xml");
			OutputStream o = http.getOutputStream();
			o.write(req.getBytes());
			o.flush();
			//這裡是成功的,有東西回來
//			DataInputStream dis = new DataInputStream(http.getInputStream());
//			String tmp;
//			while((tmp=dis.readLine())!=null){
//				System.out.println("tmp:"+tmp);
//			}
			log.trace("1");
			JAXBContext context = JAXBContext.newInstance(Login.class);
			log.trace("2");
			Unmarshaller um = context.createUnmarshaller();
			log.trace("3");
			login = (Login)um.unmarshal(http.getInputStream());
			log.trace(login.getEmployeeID());
			log.trace("4");
			http.disconnect();
		}catch (Exception ex){
			log.error("postURL error:{}",ex);
		}
		return login;
	}
}
